<?php

namespace app\common\model;

use org\util\TreeUtil;
use function PHPSTORM_META\elementType;

class ShopPromotionGroupbuyCartModel extends BaseModel
{
    protected $name = 'shop_promotion_groupbuy_cart'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = true;
    protected $updateTime = false;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改
    protected $type = [];//类型管理

    protected function getMarginStatusTextAttr($value, $data)
    {
        $arr = ['0' => '未缴纳', '1' => '已缴纳'];
        return $arr[$data['margin_status']];
    }

    protected function getIsOrderTextAttr($value, $data)
    {
        $arr = ['0' => '未转化', '1' => '已转化'];
        return $arr[$data['is_order']];
    }

    protected function getMarginTimeTextAttr($value, $data)
    {
        if ($data['margin_status'] == 0) {
            return '未缴纳';
        } else {
            return date('y-m-d H:i:s', $data['margin_time']);
        }
    }


    /**
     * 向集采购物车添加商品
     * @param int $skuId 商品sku_id
     * @param int $num 购买数量
     * @param int $uid 购买人
     * @param int $type 类型1添加修改购物车，2交付保证金
     * @return array|bool 是否添加成功
     */
    public function subCart($skuId, $num, $uid)
    {
        $model          = new ShopGoodsSkuModel();
        $goodsModel     = new ShopGoodsModel();
        $promotionModel = new ShopPromotionGroupbuyModel();
        $skuInfo        = $model->where('sku_id', $skuId)->find();
        if ($num > $skuInfo['goods_stock']) {
            $this->error = '库存不足';
            return false;
        }
        $promotion = $promotionModel->where('goods_id', $skuInfo['goods_id'])->find();
        if (time() > $promotion['end_time'] || time() < $promotion['begin_time']) {
            $this->error = '活动已经开始或者已经结束';
            return false;
        }

        $price = $goodsModel->calcPrice($skuInfo['goods_price'], $num);

        $data    = [
            'member_uid'       => $uid,
            'site_id'          => $skuInfo->goods->site_id,
            'goods_id'         => $skuInfo['goods_id'],
            'sku_id'           => $skuInfo['sku_id'],
            'goods_name'       => $skuInfo->goods->goods_name,
            'sku_name'         => $skuInfo['sku_name'],
            'goods_unit'       => $skuInfo->goods->goods_unit,
            'goods_thumb'      => $skuInfo->goods->album,
            'price'            => $price * $num,
            'num'              => $num,
            'margin'           => $promotion['margin'],
            'promotion_type'   => $skuInfo->goods->promotion_type,
            'promotion_status' => $skuInfo->goods->promotion_status,
            'cart_status'      => 1,
            'goods_price'      => $skuInfo['goods_price'],
            'goods_stock'      => $skuInfo['goods_stock'],
            'address_id'       => 0,
        ];
        $history = $this->where(['member_uid' => $uid, 'site_id' => $data['site_id'], 'goods_id' => $data['goods_id'], 'sku_id' => $data['sku_id']])->find();
        if (!$history) {
            $data['order_sn']      = 'G' . rand_number();
            $data['margin_status'] = $promotion['margin'] == 0 ? 1 : 0;
            $back                  = $this->addData($data);
        } else {
            $data['cart_id']       = $history['cart_id'];
            $back                  = $this->editData($data);
            $data['order_sn']      = $history['order_sn'];
            $data['margin_status'] = $history['margin_status'];
        }
        if ($back) {
            $orderInfo = $data;
        } else {
            $this->error = '预约失败';
            return false;
        };
        return $orderInfo;
    }


    protected function getUsernameAttr($value, $data)
    {
        $model = new UserModel();
        return $model->where('uid', $data['member_uid'])->value('username');
    }

    /**
     * 获取集采列表
     * @param int $uid 用户id
     * @param int $status 状态
     * @param int $page 第几页
     * @param int $beginTime 下单时间，默认不限制
     * @param int $endTime 下单时间，默认不限制
     * @param bool|string $name 订单号或者货物名字默认不限制
     * @param int $num 每页多少
     * @return mixed|\think\Paginator 分页类
     */
    public function getList($uid, $status, $page = 1, $beginTime = 0, $endTime = 0, $name = false, $num = 10)
    {
        $map = ['t1.member_uid' => $uid];
        switch ($status) {
            case 1:
                $map['t2.promotion_end_time'] = ['gt', time()];
                break;
            case 2:
                $map['t2.promotion_end_time'] = ['lt', time()];
                break;
        }
        if ($beginTime) {
            $map['t1.create_time'] = ['gt', time()];
        }
        if ($endTime) {
            $map['t1.create_time'] = ['lt', time()];
        }
        if ((boolean)$name) {
            $map['t1.order_sn|t1.goods_name'] = ['like', '%' . $name . '%'];
        }
        $goodsModel = new ShopGoodsModel();
        $list       = $this->alias('t1')
            ->join('shop_goods t2', 't1.goods_id=t2.goods_id')
            ->where($map)->paginate($num, false, ['page' => $page]);
        foreach ($list as $item => $value) {
            $list[$item]                     = format_goods_content($value);
            $allNum                          = $this->where('goods_id', $value['goods_id'])->sum('num');
            $list[$item]['simple_price']     = $goodsModel->calcPrice($value['goods_price'], $allNum);
            $list[$item]['all_money']        = $list[$item]['simple_price'] * $value['num'];
            $list[$item]['promotion_status'] = $goodsModel->checkPromotionGoods($value['goods_id'], '4');
            if ($list[$item]['promotion_status'] == -1) {
                $list[$item]['url'] = url('groupbuyToOrder', ['cart_id' => $value['cart_id']]);
            }
        }
        return $list;
    }

    /**
     * 获取集采详情
     * @param int $uid 用户id
     * @param int $status 状态
     * @param int $page 第几页
     * @param int $beginTime 下单时间，默认不限制
     * @param int $endTime 下单时间，默认不限制
     * @param bool|string $name 订单号或者货物名字默认不限制
     * @param int $num 每页多少
     * @return mixed|\think\Paginator 分页类
     */
    public function getInfo($uid, $cartId)
    {
        $map = ['t1.member_uid' => $uid, 't1.cart_id' => $cartId];
        $goodsModel               = new ShopGoodsModel();
        $info                     = $this->alias('t1')
            ->join('shop_goods t2', 't1.goods_id=t2.goods_id')
            ->join('shop_goods_sku t3 ', 't1.goods_id=t3.goods_id')
            ->where($map)->find();
        $info                     = format_goods_content($info);
        $allNum                   = $this->where('goods_id', $info['goods_id'])->sum('num');
        $info['simple_price']     = $goodsModel->calcPrice($info['goods_price'], $allNum);
        $info['all_money']        = $info['simple_price'] * $info['num'];
        $info['promotion_status'] = $goodsModel->checkPromotionGoods($info['goods_id'], '4');
        return $info;
    }
}
